package com.honey.mybatis.generator.entity.method;

import java.util.List;

import com.honey.compilation.java.AbstractJavaCompilation;
import com.honey.compilation.java.Method;
import com.honey.core.builder.CharacterBuilder;
import com.honey.core.builder.CharacterBuilderFactory;
import com.honey.core.compiler.IndentSpace;
import com.honey.core.dbmapping.introspect.IntrospectSchema;
import com.honey.core.dbmapping.introspect.IntrospectSchemaColumn;
import com.honey.core.dbmapping.structure.Column;
import com.honey.core.types.FullyQualifiedJavaType;
import com.honey.core.types.JDKFullyQualifiedJavaType;
import com.honey.mybatis.generator.AbstractMethod;
import com.honey.mybatis.generator.MybatisPlugin;

public class BolbToJsonObjectMethod  extends AbstractMethod {
	
	private static final String METHOD_NAME="toJSONObject";
	
	private static final FullyQualifiedJavaType RETURN_TYPE = JDKFullyQualifiedJavaType.getJSONObjectInstance();
	
	private static final String[] ANNOTATION=new String[]{
		"Override",
	};
	
	public BolbToJsonObjectMethod(AbstractJavaCompilation clazz,
			MybatisPlugin belongPlugin, IntrospectSchema introspectSchema,
			IntrospectSchemaColumn introspectSchemaColumn) {
		super(clazz, belongPlugin, introspectSchema, introspectSchemaColumn);
	}

	/*
	 * (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#getMethodName()
	 */
	@Override
	protected String getMethodName() {
		return mybatisPlugin.isEntityOverrideToJsonObject() ?  METHOD_NAME : null;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#getAnnotation()
	 */
	@Override
	protected String[] getAnnotation() {
		return ANNOTATION;
	}

	/*
	 * (non-Javadoc)
	 * @see com.honey.mybatis.generator.AbstractMethod#getReturnType()
	 */
	@Override
	protected FullyQualifiedJavaType getReturnType() {
		return RETURN_TYPE;
	}

	@Override
	protected void addBody(Method method) {
		CharacterBuilder cb = CharacterBuilderFactory.createDefaultStringBuilder();
		cb.append( "return new JSONObject()" );
		IndentSpace.newSpace(cb, 3);
		
		List<Column>  columns = introspectSchemaColumn.allColumns();
		for(Column column : columns ){
			String fieldName = super.getFieldName(column);
			
			cb.append(".put(\""+fieldName+"\",");
			if(column.getFullyQualifiedJavaType().isPrimitive()){
				cb.append("this."+fieldName);
			}else if (column.isJDBCDateColumn()){
				cb.append("this."+fieldName).append(" == null ? \"\" : ").append("this."+fieldName).append(".getTime()");
			}else {
				cb.append("this."+fieldName).append(" == null ? \"\" : ").append("this."+fieldName);
			}
			cb.append(")");
			IndentSpace.newSpace(cb, 3);
		}
		//cb.append(".toString()");
		method.addBodyLine(cb.toString());
	}

	
	
}
